package com.axjy.auth.uitl;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenUtil {

    @Value("${jwt.security}")
    private String security;

    public  String createToken(Long userId){
        JwtBuilder jwtBuilder= Jwts.builder();
        jwtBuilder.setId(userId+"")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,security);
       String token= jwtBuilder.compact();
       return token;
    }

    public  Long checkToken(String token) {
        try{
        Claims claims = Jwts.parser()
                .setSigningKey(security)
                .parseClaimsJws(token)
                .getBody();
        return Long.valueOf(claims.getId());
        }catch (Exception ex){
            return -1L;
        }
    }

}
